using System;
using System.Collections.Generic;
using System.Linq;

/// <summary>
/// 事件管理
/// </summary>
public class EventManager : Singleton<EventManager>
{
    private readonly Dictionary<string, IEnumerable<object>> _actions =
         new Dictionary<string, IEnumerable<object>>();

    /// <summary>
    /// 注册事件
    /// </summary>
    /// <typeparam name="T"></typeparam>
    /// <param name="type"></param>
    /// <param name="action"></param>
    public void Register<T>(string type, Action<T> action)
    {
        if (_actions.TryGetValue(type, out var value))
        {
            var set = value.ToHashSet();
            set.Add(action);
            _actions[type] = set;
        }
        else
        {
            var set = new HashSet<Action<T>> { action };
            _actions[type] = set;
        }
    }

    /// <summary>
    /// 注销
    /// </summary>
    /// <typeparam name="T"></typeparam>
    /// <param name="type"></param>
    /// <param name="action"></param>
    public void Unregister<T>(string type, Action<T> action)
    {
        if (!_actions.TryGetValue(type, out var value)) return;
        var set = value.ToHashSet();
        set.Remove(action);
        _actions[type] = set;
    }

    /// <summary>
    /// 发送
    /// </summary>
    /// <typeparam name="T"></typeparam>
    /// <param name="type"></param>
    /// <param name="msg"></param>
    /// <param name="stickyActions"></param>
    public void Send<T>(string type, T msg, bool stickyActions = false)
    {
        if (!_actions.TryGetValue(type, out var value)) return;
    
        foreach (var action in value.Cast<Action<T>>())
        {
            action(msg);
        }

    }
}
